package com.adnaan.backend.service.impl;

import com.adnaan.backend.common.event.BaseEvent;
import com.adnaan.backend.common.event.EventType;
import com.adnaan.backend.common.exception.ServicesException;
import com.adnaan.backend.entity.SupplierApplication;
import com.adnaan.backend.entity.SysUser;
import com.adnaan.backend.mapper.SupplierApplicationMapper;
import com.adnaan.backend.service.SupplierApplicationService;
import com.adnaan.backend.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class SupplierApplicationServiceImpl extends ServiceImpl<SupplierApplicationMapper, SupplierApplication> implements SupplierApplicationService {

    @Resource
    private SysUserService userService;

    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean audit(Long id, Integer status, String rejectReason) {
        SupplierApplication application = getById(id);
        if (application == null) {
            throw new ServicesException("申请记录不存在");
        }
        if (application.getStatus() != 0) {
            throw new ServicesException("该申请已处理");
        }

        // 更新申请状态
        application.setStatus(status);
        if (status == 2) {
            eventPublisher.publishEvent(new BaseEvent(this, application.getId(), application.getUserId(), EventType.AFTER_SALES_APPLY_REFUSE, rejectReason));
            if (rejectReason == null) {
                throw new ServicesException("拒绝时必须填写原因");
            }
        }
        if (status == 1) {
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getId, application.getUserId());
            // 通过时更改用户账号状态
            SysUser sysUser = userService.getOne(queryWrapper);
            sysUser.setStatus(1);
            eventPublisher.publishEvent(new BaseEvent(this, application.getId(), application.getUserId(), EventType.AFTER_SALES_APPLY_PASS));
            userService.updateById(sysUser);
        }

        application.setRejectReason(rejectReason);

        return updateById(application);
    }

    @Override
    public boolean isSupplier(Long userId) {
        LambdaQueryWrapper<SupplierApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SupplierApplication::getUserId, userId)
                .eq(SupplierApplication::getStatus, 1);
        return count(wrapper) > 0;
    }
} 